package com.janyee.powerdroid

import android.app.Application
import android.util.Log

import com.janyee.powerdroid.http.local.LocalResponse
import com.janyee.powerdroid.http.local.LocalResponseInterceptor
import com.janyee.powerdroid.http.Request
import com.janyee.powerdroid.http.callback.BaseCallBack
import com.janyee.powerdroid.http.callback.ICallBack
import java.util.concurrent.TimeUnit

import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor

/**
 * Created by kmlixh on 2017/2/21.
 * useage:
 * PowerDroid
 */

open class PowerApplication : Application() {
    var defaultLevel: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.NONE
    var defaultLogger: HttpLoggingInterceptor.Logger = HttpLoggingInterceptor.Logger { message -> Log.e("okhttp", message) }
    internal var localInterceptor: LocalResponseInterceptor?=null
    internal var client: OkHttpClient?=null

    fun setLocalResponseMap(localResponseMap: Map<String, LocalResponse>) {
        localInterceptor!!.localResponseMap = localResponseMap
    }

    val localResonseMap: Map<String, LocalResponse>
        get() = localInterceptor!!.localResponseMap!!

    fun setHttpLogLevel(level: HttpLoggingInterceptor.Level) {
        defaultLevel = level
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        localInterceptor = LocalResponseInterceptor()
        val logging = HttpLoggingInterceptor(defaultLogger)
        logging.level = defaultLevel
        client = OkHttpClient.Builder()
                .addInterceptor(logging)
                .addInterceptor(localInterceptor)
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build()
    }

    fun addAsyncRequest(request: Request) {
        var call= client!!.newCall(request.request)
        request.callback!!.call=call
        call.enqueue(request.callback)
    }

    fun addAsyncRequest(url: String, requestBody: RequestBody?, callback:BaseCallBack<*,*>?) {
        val builder = okhttp3.Request.Builder()
        builder.url(url)
        if (requestBody != null) {
            builder.post(requestBody)
        }
        addAsyncRequest(Request())

    }
    companion object {
        protected var instance: PowerApplication? = null

        fun s(): PowerApplication {
            return instance!!
        }
    }
}
